package com.huaxin.common.tools;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.huaxin.common.RequestApi;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by songxuefeng on 2017/8/7.
 * 平台转发
 */

public class HxTransmitRequestHelper {
    private static Retrofit        retrofit;
    private static OkHttpClient    client;
    private static RequestApi      requestApi;
    private static ListenerHandler listenerHandler;
    private static Context         mContext;
    private static final String TAG = "RequestHelper";

    public static void clearCookie() {
        mCookies = null;
    }

    private static List<Cookie> mCookies;

    public static void init(Context context, final String reuqestUrl) {
        mContext = context;
        if (listenerHandler == null) {
            listenerHandler = new ListenerHandler();
        }
        if (client == null) {
            CookieJar cookieJar1 = new CookieJar() {
                @Override
                public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                    if (url.toString().contains("/app/login")) {
                        setCookies(cookies);
                        android.util.Log.d(TAG, "saveFromResponse:---2--> " + cookies);
                    }
                }

                @Override
                public List<Cookie> loadForRequest(HttpUrl url) {
                    if (url.toString().contains(reuqestUrl)) {
                        List<Cookie> cookies = getCookies();
                        return cookies != null ? cookies : new ArrayList<Cookie>();
                    }
                    return new ArrayList<Cookie>();
                }
            };

            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    //打印retrofit日志
                    Log.i(TAG, "log message " + message);
                }
            });
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

            Interceptor downloadInterceptor = new Interceptor() {
                @Override
                public Response intercept(final Chain chain) throws IOException {
                    Response response = chain.proceed(chain.request());
                    //下载进度监听

                    return response.newBuilder()
                            .body(new ProgressResponseBody(response.body(), new ProgressListener() {
                                @Override
                                public void onProgress(long progress, long total, boolean done) {
                                    listenerHandler.obtainMessage(0, new MessageBean(chain
                                            .request().url(), progress, total, done))
                                            .sendToTarget();
                                }
                            }))
                            .build();
                }
            };

            client = new OkHttpClient.Builder()
                    .cookieJar(cookieJar1)
                    //                    .addInterceptor(loggingInterceptor)  //与progressRequest冲突
                    .addNetworkInterceptor(downloadInterceptor)
                    .readTimeout(100, TimeUnit.SECONDS)//设置读取超时时间
                    .writeTimeout(100, TimeUnit.SECONDS)//设置写的超时时间
                    .connectTimeout(100, TimeUnit.SECONDS)//设置连接超时时间
                    .build();
        }
        if (retrofit == null || !retrofit.baseUrl().equals(reuqestUrl)) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(reuqestUrl)
                    //增加返回值为String及基本数据类型的支持
                    .addConverterFactory(ScalarsConverterFactory.create())
                    //增加返回值为Gson的支持(以实体类返回)
                    .addConverterFactory(GsonConverterFactory.create())
                    //增加返回值为Oservable<T>的支持
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .client(client)
                    .build();

            requestApi = retrofit.create(RequestApi.class);
        }

        if (requestApi == null) {
            requestApi = retrofit.create(RequestApi.class);
        }

    }

    /**
     * @desc 退出登录操作
     * @author songxf
     * created at 2017/8/22 11:20
     */
    public static void getBackLogin() {
        if (client != null && retrofit != null && requestApi != null) {
            client = null;
            retrofit = null;
            requestApi = null;
        }
    }

    public static RequestApi getRequestApi() {

        if (requestApi==null){
            requestApi = retrofit.create(RequestApi.class);
        }
        return requestApi;
    }


    public static List<Cookie> getCookies() {
        android.util.Log.d("2222", "getCookies: " + mCookies);
        return mCookies;
    }

    public static void setCookies(List<Cookie> mCookies) {
        HxTransmitRequestHelper.mCookies = mCookies;
    }

    public static class ListenerHandler extends Handler {

        private Map<HttpUrl, ProgressListener> listenerMap = new HashMap<>();

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            MessageBean mBean = (MessageBean) msg.obj;
            ProgressListener pListener = listenerMap.get(mBean.getRequest());
            if (pListener != null) {
                pListener.onProgress(mBean.getProgress(), mBean.getTotal(), mBean.isDone());
                if (mBean.isDone()) {
                    listenerMap.remove(mBean.getRequest());
                }
            }

        }

        public void addListener(HttpUrl call, ProgressListener progressListener) {
            listenerMap.put(call, progressListener);
        }

        public void reconnectListener(HttpUrl call, ProgressListener progressListener) {
            if (listenerMap.containsKey(call)) {
                listenerMap.put(call, progressListener);
            }
        }

    }

    public static void addDownloadListener(HttpUrl call, ProgressListener progressListener) {
        listenerHandler.addListener(call, progressListener);
    }

    public static class MessageBean {
        private HttpUrl mRequest;
        private long    mProgress;
        private long    mTotal;
        private boolean mDone;

        public MessageBean(HttpUrl request, long progress, long total, boolean done) {
            mRequest = request;
            mProgress = progress;
            mTotal = total;
            mDone = done;
        }

        public HttpUrl getRequest() {
            return mRequest;
        }

        public long getProgress() {
            return mProgress;
        }

        public long getTotal() {
            return mTotal;
        }

        public boolean isDone() {
            return mDone;
        }
    }
}
